//
//  BoundCardController.swift
//  ShareCar
//
//  Created by jiuzhongkeji on 2019/1/4.
//  Copyright © 2019 changqingkeji. All rights reserved.
//

import UIKit
import AipOcrSdk

class BoundCardController: UIViewController {
    
    var bankInfo: User.BankInfo!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var cardNumberTextField: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.nameLabel.text = User.info()?.username
        
    }
    
    //MARK: --IBAction
    @IBAction func cameraAction(_ sender: Any) {
        
        guard let view = view else {
            return
        }
        let vc = AipCaptureCardVC.viewController(with: .bankCard) { image in
            DispatchQueue.main.async {
                self.dismiss(animated: true, completion: nil)
                JZLoading.showLoadingWith(toView: view)
            }
            AipOcrService.shard()?.detectBankCard(from: image, successHandler: { [weak self] response in
                if let result = response as? [String: AnyObject],
                    let b = result["result"] as? [String: AnyObject],
                    let value = b["bank_card_number"] as? String {
                    DispatchQueue.main.async {
                        JZLoading.hideLoading()
                        self?.cardNumberTextField.text = value
                    }
                }
            }, failHandler: { [weak self] error in
                DispatchQueue.main.async {
                    JZLoading.hideLoading()
                    self?.showError("信用卡号识别失败，请重试(2220)")
                }
            })
        }
        present(vc!, animated: true, completion: nil)
    }
    
    @IBAction func boundCardAction(_ sender: UIButton) {
        
        if !User.isAuthentication() {
            if let user = User.info() {
                let storyBoard = UIStoryboard(name: "Attestation", bundle: nil)
                switch user.certStep {
                case 0:
                    if let vc = storyBoard.instantiateViewController(withIdentifier: "IDCardViewController") as? IDCardViewController {
                        navigationController?.pushViewController(vc, animated: true)
                    }
                case 1:
                    if let vc = storyBoard.instantiateViewController(withIdentifier: "DrivingLicenseViewController") as? DrivingLicenseViewController {
                        navigationController?.pushViewController(vc, animated: true)
                    }
                case 2:
                    let vc = storyBoard.instantiateViewController(withIdentifier: "ReviewAttentationSegue")
                    navigationController?.pushViewController(vc, animated: true)
                case 3:
                    if let vc = storyBoard.instantiateViewController(withIdentifier: "RejectViewController") as? RejectViewController {
                        navigationController?.pushViewController(vc, animated: true)
                    }
                default:break
                }
            }

//            performSegue(withIdentifier: "gotoAuthSence", sender: nil)
            return
        }
        
        guard cardNumberTextField.text != "" else {
            showError("信用卡号不能为空，请重新输入（2212)")
            return
        }
        let teleiphone = cardNumberTextField.text!.removeAllSpace()
        
        guard (15...19).contains(teleiphone.count) else {
            showError("信用卡号长度不正确，请重新输入（2213）")
            return
        }
        
        JZLoading.showLoadingWith(toView: view)
        User.banckDetailInfo(bankCardId: teleiphone, success: { [weak self] info in
            JZLoading.hideLoading()
            if let info = info {
                self?.bankInfo = info
                self?.performSegue(withIdentifier: "userBankInfoSence", sender: nil)
            }
            
        }) { error in
            JZLoading.hideLoading()
            self.showError(error.msg)
        }
    }
    
    // MARK: - Navigation
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        if segue.identifier == "userBankInfoSence" {
            if let vc = segue.destination as? BoundCardInfoController {
                vc.bankInfo = self.bankInfo
                vc.bankNumber = cardNumberTextField.text?.removeAllSpace()
            }
        } else if segue.identifier == "seePayprotocolSence" {
            if let nav = segue.destination as? UINavigationController,
                let vc = nav.viewControllers.first as? WebViewController {
                vc.page = Page.server(.boundBankCard)
            }
        } else if segue.identifier == "BoundSeeBankListSence" {
            if let vc = segue.destination as? BankListViewController{
                vc.open = false
            }
        }
    }
}

extension BoundCardController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        var text = textField.text! as NSString
        //设置格式为数字
        let characterSet = NSCharacterSet(charactersIn: "0123456789")
        //去掉空格
        
        let str = string.replacingOccurrences(of: " ", with: "")
        let nsStr = str as NSString
        if nsStr.rangeOfCharacter(from: characterSet.inverted).location != NSNotFound {
            return false
        }
        //将输入的数字添加给textfield
        text = text.replacingCharacters(in: range, with: string) as NSString
        //去掉空格
        text = text.replacingOccurrences(of: " ", with: "") as NSString
        
        var newString = ""
        while text.length > 0 {
            let substring = text.substring(to: getMin(num1: text.length, num2: 4))
            newString = newString.appendingFormat(substring)
            if substring.count == 4 {
                newString = newString.appendingFormat(" ")
            }
            text = text.substring(from: getMin(num1: text.length, num2: 4)) as NSString
        }
        
        newString = newString.trimmingCharacters(in: characterSet.inverted)
        if newString.count >= 24 { //设置银行卡位数为16
            return false
        }
        textField.text = newString
        
        if string.bytes.first == nil {
            var loc = range.location
            if loc > newString.count {
                loc = newString.count
            }
            let r = NSRange(location: loc, length: 0)
            textField.setSelectedRange(r)
        } else if nsStr.rangeOfCharacter(from: characterSet.inverted).location == NSNotFound {
            var loc = range.location + 1
            if loc % 5 == 0 {
                loc += 1
            }
            let r = NSRange(location: loc, length: 0)
            textField.setSelectedRange(r)
        }
        return false
        
    }
    
    func getMin(num1 : Int, num2: Int) -> Int {
        if num1 <= num2 {
            return num1
        } else {
            return num2
        }
    }

}
